﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;

namespace WP8_Client.CustomObjects
{
    public class LocationController
    {
        Geolocator cGeolocator;
        BackgroundWorker cLocationWorker;
        public delegate void LocationEventHandler(Location pLocation);
        public event LocationEventHandler OnUpdateLocation;
               

        public LocationController()
        {
            this.cGeolocator = new Geolocator();
            this.cLocationWorker = new BackgroundWorker();
            this.cLocationWorker.DoWork += cLocationWorker_DoWork;
            this.cLocationWorker.RunWorkerCompleted += (obj, e) => { this.cLocationWorker.RunWorkerAsync(this.cGeolocator); };
        }

        public void Start()
        {
            this.cLocationWorker.RunWorkerAsync(this.cGeolocator);
        }
        public void Stop()
        {
            this.cLocationWorker.CancelAsync();
        }

        void cLocationWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!this.cLocationWorker.CancellationPending)
            {
                this.GetLocation((Geolocator)e.Argument);
                Thread.Sleep(Globals.LocationController.UpdateInterval);
            }
            e.Cancel = true;                 
        }
        private async void GetLocation(Geolocator pGeoLocator)
        {
            pGeoLocator.DesiredAccuracyInMeters = Globals.LocationController.DesiredAccuracyInMeters;
            try
            {
                Geoposition geoposition = await pGeoLocator.GetGeopositionAsync();
                if (this.OnUpdateLocation != null)
                    this.OnUpdateLocation(new Location() { Latitude = geoposition.Coordinate.Latitude, Longitude = geoposition.Coordinate.Longitude });
            }
            catch (Exception e)
            {
                if ((uint)e.HResult == 0x80004004)
                {
                    // the application does not have the right capability or the location master switch is off                    
                }
                else
                {
                    // something else happened acquring the location
                }
            }
        }
    }
}
